<template>
  <view class="add-product-container bg-white">
    <view scroll-y class="content">
	  <view style="height: 30rpx;"></view>
      <!-- 产品名称 -->
      <view class="form-item">
        <u--input
          v-model="productName"
          placeholder="请输入产品名称"
          border="bottom"
          clearable
        ></u--input>
      </view>
      
      <!-- 产品图片上传 -->
      <view class="form-item">
        <view class="upload-title">
          <text>产品图片</text>
          <text class="tips">(最多9张，推荐尺寸512*512)</text>
        </view>
        
        <!-- 图片列表 -->
            <view class="image-list">
              <!-- 已上传图片 -->
              <view 
                v-for="(item, index) in imageList" 
                :key="index" 
                class="image-item"
              >
                <image 
                  :src="item.url" 
                  mode="aspectFill" 
                  class="image"
                  @click="previewImage(index)"
                ></image>
                
                <!-- 上传中的Loading效果 -->
                <view v-if="item.uploading" class="uploading-mask">
                  <u-loading-icon color="#fff"></u-loading-icon>
				  <view class="progress-text">上传中</view>
                </view>
                
                <u-icon 
                  name="close-circle-fill" 
                  color="#f56c6c" 
                  size="20" 
                  class="delete-icon"
                  @click="removeImage(index)"
                  :style="{opacity: item.uploading ? 0.5 : 1}"
                ></u-icon>
              </view>
              
              <!-- 上传按钮 -->
              <view 
                v-if="imageList.length < maxCount" 
                class="upload-btn" 
                @click="chooseImage"
                :class="{disabled: uploadingCount > 0}"
              >
                <u-icon name="plus" size="28" color="#c0c4cc"></u-icon>
                <text class="upload-text">添加图片</text>
              </view>
            </view>
      </view>
      
      <!-- 产品描述 -->
      <view class="form-item">
        <view class="editor-title">产品描述</view>
        <editor
          id="editor"
          class="editor"
          placeholder="请输入产品描述..."
          @ready="onEditorReady"
          @input="onEditorInput"
          @statuschange="onStatusChange"
        ></editor>
		<view class="mt-10" style="width: 200rpx;">
			<u-button
			@click="insertImage"
			  type="info"
			  size="small"
			  shape="circle" 
			  text="插入图片"
			></u-button>
		</view>
      </view>
	  
    </view>
    
    <!-- 底部按钮 -->
    <view class="footer" :style="{paddingBottom: safeAreaInsets.bottom + 'px'}">
      <u-button 
        type="error" 
        shape="circle" 
        text="删除" 
        @click="handleDelete"
        v-if="isEdit"
      ></u-button>
      <u-button 
        type="primary" 
        shape="circle" 
        text="确定" 
        @click="handleSubmit"
      ></u-button>
    </view>
		<u-toast ref="toast"></u-toast>
  </view>
</template>

<script>
	import api from "@/api/api";
export default {
  data() {
    return {
      productName: '',
      imageList: [],
	  maxCount: 9,
	  uploadingCount: 0,
      productDesc: '',
      editorCtx: null,
      isEdit: false, // 是否编辑模式
      safeAreaInsets: {
        bottom: 0
      },
	  editId: null,
	  editProduct: null
    }
  },
  async onLoad(options) {
    // 获取底部安全区域
    this.safeAreaInsets = uni.getSystemInfoSync().safeAreaInsets
    
    // 如果是编辑模式，加载已有数据
    if (options.id) {
      this.isEdit = true
	  this.editId = options.id;
      await this.loadProductData(options.id)
    }
  },
  methods: {
    // 加载产品数据
    async loadProductData(id) {
      // 这里应该是从API获取数据
	  let res = await this.depot.get(api.aiCard("product/findOne?id=" + id));
	  let product = res && res.data && res.data.data ? res.data.data : null;
	  this.editProduct = product;
	  this.productName = product.name;
      this.productDesc = product.description;
	  res = await this.depot.post(api.aiCard("productImage/findProductImagePage?page=0&size=100"), {
		  productId: id
	  })
	  let imgList = res && res.data && res.data.data && res.data.data.content ? res.data.data.content : [];
	  if (imgList && imgList.length > 0) {
		  for(let imgInfo of imgList) {
			  this.imageList.push({
				  url: imgInfo.imgUrl,
				  uploadedUrl: imgInfo.imgUrl
			  });
		  }
	  }
    },
    
    async chooseImage() {
          if (this.uploadingCount > 0) {
            uni.showToast({ title: '有图片正在上传', icon: 'none' })
            return
          }
          
          try {
            const res = await uni.chooseImage({
              count: this.maxCount - this.imageList.length,
              sizeType: ['compressed'],
              sourceType: ['album', 'camera']
            })
            
            // 添加到列表并开始上传
            res.tempFilePaths.forEach(path => {
              this.startUpload(path)
            })
          } catch (error) {
            console.error('选择图片失败:', error)
          }
        },
        
        async startUpload(filePath) {
          const item = {
            url: filePath, // 先显示本地路径
            uploading: true,
            progress: 0
          }
          this.imageList.push(item)
          this.uploadingCount++
          
		  const imageUrl = await this.uploadImage(filePath);
		  console.log("imageUrl", imageUrl)
		  item.uploadedUrl = imageUrl;
		  this.finishUpload(item, false)
        },
        
        finishUpload(item, isError = false) {
          this.uploadingCount--
          if (isError) {
            this.imageList = this.imageList.filter(i => i !== item)
            uni.showToast({ title: '上传失败', icon: 'none' })
          } else {
            item.uploading = false
            item.progress = 0
          }
        },
        
        removeImage(index) {
          if (this.imageList[index].uploading) {
            uni.showToast({ title: '图片上传中，不能删除', icon: 'none' })
            return
          }
          this.imageList.splice(index, 1)
        },
        
        previewImage(index) {
          if (this.imageList[index].uploading) return
          
          uni.previewImage({
            current: this.imageList[index].url,
            urls: this.imageList.filter(item => !item.uploading).map(item => item.url)
          })
        },
		
    
    // 编辑器相关方法
    onEditorReady() {
      uni.createSelectorQuery()
        .in(this)
        .select('#editor')
        .context((res) => {
          this.editorCtx = res.context
          // 如果是编辑模式，设置编辑器内容
          if (this.isEdit) {
            this.editorCtx.setContents({
              html: this.productDesc
            })
          }
        })
        .exec()
    },
    
    onEditorInput(e) {
      this.productDesc = e.detail.html
    },
    
    onStatusChange(e) {
      console.log('编辑器状态变化:', e.detail)
    },
    
    // 删除产品
    handleDelete() {
      uni.showModal({
        title: '提示',
        content: '确定要删除该产品吗？',
        success: (res) => {
          if (res.confirm) {
            // 调用删除API
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
            setTimeout(() => {
              uni.navigateBack()
            }, 1500)
          }
        }
      })
    },
    
    // 提交表单
    async handleSubmit() {
      if (!this.productName) {
		  this.$refs.toast.show({
		  	type: "error",
		  	title: "提示",
		  	message: "请输入产品名称"
		  });
        return
      }
      
      if (this.imageList.length === 0) {
		  this.$refs.toast.show({
		  	type: "error",
		  	title: "提示",
		  	message: "请上传至少一张产品图片"
		  });
        return
      }
	  
	  let res = await this.editorCtx.getContents()
	  let description = res.html;
	  if (!description) {
		  this.$refs.toast.show({
		  	type: "error",
		  	title: "提示",
		  	message: "请输入产品描述"
		  });
	  }
      // 这里应该是调用API提交数据
      uni.showLoading({
        title: '提交中...'
      })
      
	  let productImageList = [];
	  this.imageList.forEach(imageInfo => {
		  productImageList.push(imageInfo.uploadedUrl);
	  })
	  let product = {
		  name: this.productName,
		  description: this.productDesc,
		  productImageUrlList: productImageList
	  }
	  if (this.isEdit) {
		  this.editProduct.name = this.productName;
		  this.editProduct.description = this.productDesc;
		  this.editProduct.productImageUrlList = productImageList.reverse();
	  } else {
		  this.editProduct = product;
	  }
	  res = await this.depot.post(api.aiCard("product/saveProduct"), this.editProduct).finally(() => {
		  uni.hideLoading()
	  })
	  this.$refs.toast.show({
	  	type: "success",
	  	title: "提示",
	  	message: "提交成功"
	  });
	  if (this.isEdit) {
		  uni.$emit("editProductSuccess", this.editProduct);
	  } else {
		  let product = res && res.data && res.data.data ? res.data.data : null;
		  uni.$emit("createProductSuccess", product);
	  }
	  setTimeout(() => {
	    uni.navigateBack()
	  }, 1500)
    },
	async insertImage() {
	    // 选择图片
	    const res = await uni.chooseImage({
	      count: 1,
	      sizeType: ['compressed']
	    });
	    console.log("res1", res)
	    // 上传图片获取URL（示例代码需替换实际API）
	    let imageUrl = await this.uploadImage(res.tempFilePaths[0]);
		// imageUrl = imageUrl ? imageUrl + "?x-oss-process=image/resize,w_512,h_512,m_fast" : null;
	    console.log("imageUrl", imageUrl)
	    // 插入到编辑器
		if (imageUrl) {
			this.editorCtx.insertImage({
			  src: imageUrl,
			  alt: '产品图片',
			  width: '100%'
			});
		}
	  },
	  
	  async uploadImage(filePath) {
		let res = await this.depot.uploadFile(
				api.document("document/uploadDocument"), filePath)
			.catch(err => {});
		if (res && res.data && res.data.accessUrl) {
			return res.data.accessUrl;
		}
		return null;
	  },
  }
}
</script>

<style lang="less">
.add-product-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  
  .content {
	padding: 0rpx 30rpx;
	overflow-y: auto;
	height: calc(100vh - 100rpx - env(safe-area-inset-bottom));
  }
  
  .form-item {
    margin-bottom: 40rpx;
    
    .upload-title, .editor-title {
      font-size: 28rpx;
      color: #606266;
      margin-bottom: 20rpx;
      display: flex;
      align-items: center;
      
      .tips {
        font-size: 24rpx;
        color: #909399;
        margin-left: 10rpx;
      }
    }
  }
  
    .image-list {
      display: flex;
      flex-wrap: wrap;
      margin: 0 -8rpx;
      
      .image-item, .upload-btn {
        width: calc(33.33vw - 36rpx);
        height: calc(33.33vw - 36rpx);
        // padding-bottom: calc(33.33% - 16rpx);
        margin: 8rpx;
        position: relative;
        border-radius: 8rpx;
        overflow: hidden;
      }
      
      .image-item {
        background-color: #f5f7fa;
        
        .image {
          width: 100%;
          height: 100%;
          position: absolute;
          top: 0;
          left: 0;
        }
        
        .uploading-mask {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background-color: rgba(0, 0, 0, 0.5);
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          color: #fff;
          
          .progress-text {
            font-size: 24rpx;
            margin-top: 10rpx;
          }
        }
        
        .delete-icon {
          position: absolute;
          top: 0;
          right: 0;
          z-index: 2;
          padding: 8rpx;
        }
      }
      
      .upload-btn {
        border: 1px dashed #c0c4cc;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        
        &.disabled {
          opacity: 0.5;
        }
        
        .upload-text {
          font-size: 24rpx;
          color: #909399;
          margin-top: 10rpx;
        }
      }
    }
  
  .editor {
    min-height: 400rpx;
    background-color: #fff;
    padding: 20rpx;
    border-radius: 8rpx;
    border: 1px solid #dcdfe6;
  }
  
  .footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20rpx 30rpx;
    background-color: #fff;
    display: flex;
    box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.05);
    
    .u-button {
      flex: 1;
      margin: 0 10rpx;
    }
  }
}
</style>
